<?php

namespace App\Exports;

use App\Models\EnterLog;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;


class EnterLogExport implements FromCollection,WithHeadings,WithMapping
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $query=EnterLog::query()->with(['user','housings','housingsorder']);
        if (isset($this->filters['ids'])) {
            $query->whereIn('id', explode(',',$this->filters['ids']));
        }
        return $query->get();
    }

    public function headings(): array
    {
        return [
            '入住人员ID',
            '姓名',
            '电话',
            '性别',
            '排房订单号',
            '房源码',
            '入住时间',
            '退房时间',
            '数据更新时间',
            '数据推送时间',
            // ... 其他列标题
        ];
    }

    public function map($enterlog): array
    {
        // 假设订单有 id 和 total 字段

        $orderData[] = [
            $enterlog['user_id'],
            $enterlog['real_name']=isset($enterlog['user']['real_name']) ? $enterlog['user']['real_name'] :'',
            $enterlog['phone_number']=isset($enterlog['user']['phone_number']) ? $enterlog['user']['phone_number'] :'',
            $enterlog['gender']=isset($enterlog['user']['gender']) ? $enterlog['user']['gender'] :'',
            $enterlog['sn']=isset($enterlog['housingsorder']['sn']) ? $enterlog['housingsorder']['sn'] :"",
            $enterlog['housings_num']=isset($enterlog['housings']['housings_num']) ? $enterlog['housings']['housings_num'] :"",
            $enterlog['enter_at'],
            $enterlog['exit_at'],
            "",
            "",
        ];

        // 展开订单数据，以便每行都有用户信息和对应的订单信息
        return array_merge(...$orderData);
    }
}
